from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
import os
from crypto_utils import verify_login_token

class TokenMiddleware:
    def __init__(self, app):
        self.app = app
    
    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return
            
        request = Request(scope, receive)
        
        # 获取请求路径
        path = request.url.path
        
        # 排除不需要验证的路由和静态文件
        excluded_paths = ["/", "/login"]
        if path in excluded_paths or path.startswith("/uploads/"):
            await self.app(scope, receive, send)
            return
        
        # 获取token
        auth_header = request.headers.get("authorization")
        if not auth_header or not auth_header.startswith("Bearer "):
            response = JSONResponse(
                content={"error": "非法请求"},
                status_code=401
            )
            await response(scope, receive, send)
            return
            
        token = auth_header.split(" ")[1]
        
        # 验证token
        if not verify_login_token(token):
            response = JSONResponse(
                content={"error": "非法请求"},
                status_code=401
            )
            await response(scope, receive, send)
            return
        
        # token验证通过，继续处理请求
        await self.app(scope, receive, send)